import { defineStore } from 'pinia';
import axios from 'axios';
import request from '../utils/request';

// 分类数据类型定义
export interface Category {
  id: number;
  name: string;
  description: string;
  question_count: number;
  icon: string; // 图标类名（如"fa-code"）
  color: string; // 颜色类名（如"text-primary"）
  children:Category[];
}

// 定义Store
export const useCategoryStore = defineStore('category', {
  state: (): {
    categories: Category[];
    currentCategory: Category | null;
    loading: boolean;
    error: string | null;
  } => ({
    categories: [],
    currentCategory: null,
    loading: false,
    error: null
  }),

  getters: {
    // 获取分类数量
    categoryCount: (state) => state.categories.length,
    
    // 判断是否有当前分类
    hasCurrentCategory: (state) => !!state.currentCategory,
    
    // 获取热门分类（问题数最多的前5个）
    hotCategories: (state) => {
      // 复制数组并按问题数降序排序
      return [...state.categories]
        .sort((a, b) => (b.question_count || 0) - (a.question_count || 0))
        .slice(0, 5);
    }
  },

  actions: {
    // 重置状态
    resetState(): void {
      this.categories = [];
      this.currentCategory = null;
      this.error = null;
    },

    // 获取所有分类
    async fetchAllCategories(): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        const response = await request.get('/api/categories/tree',{},{
          minLoadingTime:2000
        });
        this.categories = response.data.categoryTree;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取分类失败';
        console.error(this.error);
      } finally {
        this.loading = false;
      }
    },

    // 获取分类详情
    async fetchCategoryDetail(id: number): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        const response = await axios.get<Category>(`/api/categories/${id}`);
        this.currentCategory = response.data;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取分类详情失败';
        console.error(this.error);
      } finally {
        this.loading = false;
      }
    }
  }
});
    